package com.dangdang.service.impl;

import com.dangdang.dao.CategoryDao;
import com.dangdang.entity.Category;
import com.dangdang.service.CategoryService;
import com.dangdang.util.MyBatisUtil;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

public class CategoryServiceImpl implements CategoryService {
    @Override
    public List<Category> selectAllCate() {
        SqlSession sqlSession = null;
        List<Category> categories = null;
        try {
            sqlSession = MyBatisUtil.getSqlSession();
            CategoryDao dao = sqlSession.getMapper(CategoryDao.class);
            categories = dao.selectAllCate();
            sqlSession.commit();
        } catch (Exception e) {
            sqlSession.rollback();
            e.printStackTrace();
            throw new RuntimeException(e);
        } finally {
            MyBatisUtil.closeSqlSession(sqlSession);
        }
        return categories;
    }

    @Override
    public List<Category> selectCounts(int id) {
        SqlSession sqlSession = null;
        List<Category> categories = null;
        try {
            sqlSession = MyBatisUtil.getSqlSession();
            CategoryDao dao = sqlSession.getMapper(CategoryDao.class);
            categories = dao.selectCounts(id);
            sqlSession.commit();
        } catch (Exception e) {
            sqlSession.rollback();
            e.printStackTrace();
            throw new RuntimeException(e);
        } finally {
            MyBatisUtil.closeSqlSession(sqlSession);
        }
        return categories;
    }

    @Override
    public Category selectByCid(int cid) {
        SqlSession sqlSession = null;
        Category category = null;
        try {
            sqlSession = MyBatisUtil.getSqlSession();
            CategoryDao dao = sqlSession.getMapper(CategoryDao.class);
            category = dao.selectByCid(cid);
            sqlSession.commit();
        } catch (Exception e) {
            sqlSession.rollback();
            e.printStackTrace();
            throw new RuntimeException(e);
        } finally {
            MyBatisUtil.closeSqlSession(sqlSession);
        }
        return category;
    }
}
